package com.servlet;

import com.sun.org.apache.xpath.internal.objects.XObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author com.com.hyl
 * @Date 2022/9/17 8:47
 **/
@WebServlet(name = "DispatcherServlet",urlPatterns = "/do/*")
public class DispatcherServlet extends HttpServlet {

	//通过核心控制器==》判断执行的类和方法

	private Map<String,String> mapping ;

	@Override
	public void init() throws ServletException {
		mapping = new HashMap<String,String>();
		mapping.put("/user/login","com.servlet.LoginServlet");
		mapping.put("/user/reg","com.servlet.LoginServlet");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(request.getPathInfo()); //==>/user/login
		//执行
		execute(request, response);
	}

	protected void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pathKey = request.getPathInfo();
		try {
			Class clz = Class.forName(mapping.get(pathKey)); //加载==》com.servlet.LoginServlet

			Object obj = clz.newInstance(); //创建对象
			String methodName = pathKey.substring(pathKey.lastIndexOf("/")+1);
			System.out.println("方法名："+methodName);

			Method method = obj.getClass().getMethod(methodName,
					HttpServletRequest.class,
					HttpServletResponse.class);
			method.setAccessible(true); //设置访问权限
			//调用方法
		    Object ret =  method.invoke(obj, request,response);

		    //判断结果类型==》ajax / 转发 / 重定向
			toView(ret, request,response);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}


	public void toView(Object ret,HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("utf-8");
		//判断
		if (ret ==null){
			return ;
		}
		String msg = (String) ret;
		if (msg.startsWith("out:")){ //ajax
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out  = response.getWriter();
			out.print(msg); //打印
			out.flush();
			out.close();
		}else if(msg.startsWith("redirect:")){
			response.sendRedirect(msg.substring(9));
		}
		System.out.println(msg);
	}
}
